package com.hiwan.system.main;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.naming.NamingException;

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.webapp.WebAppContext;
import org.springframework.util.ResourceUtils;

import com.hiwan.platform.util.LangUtil;
/**
 * 运行项目有两种方式：
 * 
 * ⑴直接运行JettyStarter,要在config/config.properties进行配置。
 * ⑵运行Maven的Jetty插件，其优点是能做到热部署。
 * 	 	Run As→Run Configurations 
 * 		→1、在Browse Workspace 选中项目
 * 		→2、Goles中输入 ：jetty:run 
 * 		→3、勾选 resolve workspace artifactId
 * @author lsb
 * @date 2015年12月2日 下午4:48:30
 * @version hiwan3.0
 */
public class JettyStarter {
	public static void main(String[] args) throws IOException, NamingException {
		startJetty();
	}
	
	public static void startJetty() throws NamingException, IOException {
		Properties props = readProperties();

		Server server = new Server();
		//
		QueuedThreadPool threadPool = new QueuedThreadPool();
		threadPool.setMinThreads(10);
		threadPool.setMaxThreads(200);
		server.setThreadPool(threadPool);

		//
		SelectChannelConnector connector = new SelectChannelConnector();
		connector.setPort(LangUtil.parseInt(props.get("com.hiwan.server.port")));
		connector.setMaxIdleTime(3000);
		connector.setAcceptors(Runtime.getRuntime().availableProcessors() + 1);
		connector.setStatsOn(false);
		connector.setLowResourcesConnections(32000);
		connector.setLowResourcesMaxIdleTime(60000 * 10);
		server.setConnectors(new Connector[] { connector });

		//
		WebAppContext webAppContext = new WebAppContext();
		webAppContext.setClassLoader(null);

		webAppContext.setClassLoader(Thread.currentThread().getContextClassLoader());
		webAppContext.setDescriptor("/webdefault.xml");

		String resourceBase = props.getProperty("com.hiwan.test.webapp.path");
		String contextPath = props.getProperty("com.hiwan.test.webRoot");
		System.out.println("RESOURCE_BASE : " + resourceBase);
		System.out.println("CONTEX_PATH : " + contextPath);

		webAppContext.setResourceBase(resourceBase);
		webAppContext.setContextPath(contextPath);
		//
		server.setHandler(webAppContext);
		server.setStopAtShutdown(true);
		server.setSendServerVersion(false);
		server.setSendDateHeader(false);
		server.setGracefulShutdown(1000);

		//
		try {
			server.start();
			server.join();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static Properties readProperties() throws IOException {
		File configFile = ResourceUtils.getFile("classpath:config/config.properties");
		
		Properties props = new Properties();
		InputStream in = new BufferedInputStream(new FileInputStream(configFile));
		props.load(in);
		return props;
	}
	
	
}
